package main

import (
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/middleware"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/repo"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/repo/dao"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/service"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/web"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

func main() {
	s := gin.Default()
	// 解决跨域问题
	s.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"http://localhost:8080"},  // 允许的前端地址
		AllowMethods:     []string{"GET", "POST", "OPTIONS"}, // 允许的方法
		AllowHeaders:     []string{"Content-Type"},
		AllowCredentials: true, // 允许携带凭证（如 Cookies）
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers"},
		MaxAge:           12 * time.Hour, // 缓存预检请求的时间
	}))
	s.Use(middleware.NewAuthMiddleware().IgnorePaths("/user/login").Build())
	//store := cookie.NewStore([]byte("secret"))
	//store := memstore.NewStore([]byte("secret"), []byte("auth"))
	//store, err := redis.NewStore(16, "tcp", "localhost:6379", "", []byte("secret"), []byte("auth"))
	//if err != nil {
	//	panic("redis连接失败")
	//}
	//s.Use(sessions.Sessions("mysession", store))

	// 初始化数据库
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:13306)/bingweb"))
	if err != nil {
		panic("数据库初始化失败")
	}
	// 建表
	err = dao.InitTables(db)
	if err != nil {
		panic("数据表创建失败")
	}
	// 初始化对象
	u := &web.UserHandle{Svc: &service.UserService{Repo: &repo.UserRepo{Dao: &dao.UserDao{Db: db}}}}
	// 注册路由
	u.RegisterRouter(s)

	s.Run(":9999")
}
